#include <iostream>
#include <string>
#include <sstream>
#include <cstring>
#include <linenoise.h>
#include "utils_ipc.h"
#include "utils_log.h"
#include "utils_init.h"
#include <nlohmann/json.hpp>

int main(int argc, char *argv[])
{
    nlohmann::json config;
    config["log_level"] = "info";
    config["log_to_file"] = false;
    El::Utils::base_init(config);

    EL_INFO("EL Shell Client starting...");

    // 创建IPC客户端 - 使用正确的Client类
    El::Utils::Client client("shell_service");

    if (!client.connect()) {
        EL_ERROR("无法连接到Shell服务");
        return 1;
    }

    EL_INFO("已连接到Shell服务. 输入'help'查看可用命令，输入'exit'或'quit'退出。");

    // 如果有命令行参数，执行参数中的命令后退出
    if (argc > 1) {
        std::ostringstream cmdLine;
        for (int i = 1; i < argc; i++) {
            if (i > 1)
                cmdLine << " ";
            cmdLine << argv[i];
        }

        std::string cmd = cmdLine.str();
        EL_INFO("执行命令: {}", cmd);

        El::Utils::Message request, response;
        request.setData(cmd);

        if (client.sendMessage(request, response)) {
            EL_INFO("命令执行成功: {}", response.getData());
        } else {
            EL_ERROR("命令执行失败");
        }

        return 0;
    }

    // 交互式命令行
    char *line;
    while ((line = linenoise("el> ")) != nullptr) {
        std::string input(line);

        if (input.empty()) {
            free(line);
            continue;
        }

        // 添加到历史记录
        linenoiseHistoryAdd(line);

        // 处理退出命令
        if (input == "exit" || input == "quit") {
            free(line);
            break;
        }

        // 发送命令到服务端
        El::Utils::Message request, response;
        request.setData(input);

        if (client.sendMessage(request, response)) {
            EL_INFO("命令执行成功: {}", response.getData());
        } else {
            EL_ERROR("命令执行失败");
        }

        free(line);
    }

    EL_INFO("EL Shell Client exiting...");
    EL_INFO("再见！");

    // 断开连接
    client.disconnect();

    return 0;
}
